<template>
  <div class="profile">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>个人资料</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button
                v-if="!isEditing"
                type="primary"
                size="small"
                @click="handleEdit"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <div v-else class="edit-actions">
                <el-button size="small" @click="handleCancel">
                  取消
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  :loading="loading"
                  @click="handleSave"
                >
                  保存
                </el-button>
              </div>
            </div>
          </template>
          
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            :disabled="!isEditing"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名">
                  <el-input v-model="profileForm.username" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名" prop="realName">
                  <el-input
                    v-model="profileForm.realName"
                    placeholder="请输入真实姓名"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="profileForm.email"
                    placeholder="请输入邮箱地址"
                    type="email"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电话" prop="phone">
                  <el-input
                    v-model="profileForm.phone"
                    placeholder="请输入手机号码"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="角色">
                  <el-input v-model="roleText" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-tag :type="statusType" size="large">
                    {{ statusText }}
                  </el-tag>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="部门" prop="department">
                  <el-input
                    v-model="profileForm.department"
                    placeholder="请输入所属部门"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职位" prop="position">
                  <el-input
                    v-model="profileForm.position"
                    placeholder="请输入职位"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="最后登录">
              <el-input v-model="lastLoginText" disabled />
            </el-form-item>
            
            <el-form-item label="注册时间">
              <el-input v-model="createdAtText" disabled />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <!-- 头像和快速操作 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <!-- 头像卡片 -->
        <el-card class="avatar-card">
          <template #header>
            <span>头像</span>
          </template>
          
          <div class="avatar-section">
            <el-avatar :size="120" :src="profileForm.avatar">
              <el-icon size="60"><User /></el-icon>
            </el-avatar>
            
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
            >
              <el-button type="primary" size="small">
                <el-icon><Upload /></el-icon>
                更换头像
              </el-button>
            </el-upload>
            
            <p class="avatar-tip">
              支持 JPG、PNG 格式，文件大小不超过 2MB
            </p>
          </div>
        </el-card>
        
        <!-- 密码修改卡片 -->
        <el-card class="password-card">
          <template #header>
            <span>密码管理</span>
          </template>
          
          <div class="password-section">
            <p class="password-info">
              为了您的账户安全，建议定期更换密码
            </p>
            
            <el-button
              type="warning"
              style="width: 100%"
              @click="showPasswordDialog = true"
            >
              <el-icon><Lock /></el-icon>
              修改密码
            </el-button>
          </div>
        </el-card>
        
        <!-- 账户统计卡片 -->
        <el-card class="stats-card">
          <template #header>
            <span>账户统计</span>
          </template>
          
          <div class="stats-list">
            <div class="stats-item">
              <span class="stats-label">登录次数</span>
              <span class="stats-value">{{ accountStats.loginCount }}</span>
            </div>
            <div class="stats-item">
              <span class="stats-label">在线时长</span>
              <span class="stats-value">{{ accountStats.onlineTime }}</span>
            </div>
            <div class="stats-item">
              <span class="stats-label">操作记录</span>
              <span class="stats-value">{{ accountStats.operationCount }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlePasswordCancel">取消</el-button>
          <el-button
            type="primary"
            :loading="passwordLoading"
            @click="handlePasswordSubmit"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user.store'

const userStore = useUserStore()

// 响应式数据
const profileFormRef = ref()
const passwordFormRef = ref()
const isEditing = ref(false)
const loading = ref(false)
const passwordLoading = ref(false)
const showPasswordDialog = ref(false)

const profileForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  role: '',
  status: '',
  department: '',
  position: '',
  avatar: '',
  lastLoginAt: '',
  createdAt: ''
})

const originalProfileForm = reactive({})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const accountStats = reactive({
  loginCount: 156,
  onlineTime: '128小时',
  operationCount: 1024
})

// 表单验证规则
const profileRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { 
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, 
      message: '密码必须包含大小写字母和数字', 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const roleText = computed(() => {
  const roleMap = {
    admin: '管理员',
    doctor: '医生',
    nurse: '护士',
    operator: '操作员'
  }
  return roleMap[profileForm.role] || '未知'
})

const statusType = computed(() => {
  return profileForm.status === 'active' ? 'success' : 'danger'
})

const statusText = computed(() => {
  return profileForm.status === 'active' ? '正常' : '禁用'
})

const lastLoginText = computed(() => {
  if (!profileForm.lastLoginAt) return '从未登录'
  return formatDateTime(profileForm.lastLoginAt)
})

const createdAtText = computed(() => {
  if (!profileForm.createdAt) return ''
  return formatDateTime(profileForm.createdAt)
})

// 方法
const loadUserProfile = async () => {
  try {
    await userStore.getCurrentUser()
    const userInfo = userStore.userInfo
    if (userInfo) {
      Object.assign(profileForm, {
        username: userInfo.username || '',
        realName: userInfo.realName || '',
        email: userInfo.email || '',
        phone: userInfo.phone || '',
        role: userInfo.role || '',
        status: userInfo.status || '',
        department: userInfo.department || '',
        position: userInfo.position || '',
        avatar: userInfo.avatar || '',
        lastLoginAt: userInfo.lastLoginAt || '',
        createdAt: userInfo.createdAt || ''
      })
      
      // 保存原始数据
      Object.assign(originalProfileForm, profileForm)
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

const handleEdit = () => {
  isEditing.value = true
}

const handleCancel = () => {
  isEditing.value = false
  // 恢复原始数据
  Object.assign(profileForm, originalProfileForm)
  profileFormRef.value?.clearValidate()
}

const handleSave = async () => {
  try {
    await profileFormRef.value.validate()
    
    loading.value = true
    
    const updateData = {
      realName: profileForm.realName,
      email: profileForm.email,
      phone: profileForm.phone,
      department: profileForm.department,
      position: profileForm.position
    }
    
    await userStore.updateCurrentUser(updateData)
    
    // 更新原始数据
    Object.assign(originalProfileForm, profileForm)
    
    isEditing.value = false
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    ElMessage.error('个人信息更新失败')
  } finally {
    loading.value = false
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const handleAvatarUpload = (options) => {
  // 这里应该实现头像上传逻辑
  // 暂时模拟上传成功
  const reader = new FileReader()
  reader.onload = (e) => {
    profileForm.avatar = e.target.result
    ElMessage.success('头像上传成功')
  }
  reader.readAsDataURL(options.file)
}

const handlePasswordCancel = () => {
  showPasswordDialog.value = false
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  passwordFormRef.value?.clearValidate()
}

const handlePasswordSubmit = async () => {
  try {
    await passwordFormRef.value.validate()
    
    passwordLoading.value = true
    
    await userStore.changePassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    })
    
    showPasswordDialog.value = false
    handlePasswordCancel()
    ElMessage.success('密码修改成功')
  } catch (error) {
    ElMessage.error('密码修改失败')
  } finally {
    passwordLoading.value = false
  }
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.profile {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.page-header h2 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.profile-card,
.avatar-card,
.password-card,
.stats-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-actions {
  display: flex;
  gap: 8px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-tip {
  margin: 0;
  font-size: 12px;
  color: #909399;
  text-align: center;
  line-height: 1.4;
}

.password-section {
  text-align: center;
}

.password-info {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.stats-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stats-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stats-item:last-child {
  border-bottom: none;
}

.stats-label {
  font-size: 14px;
  color: #606266;
}

.stats-value {
  font-size: 14px;
  font-weight: 600;
  color: #409EFF;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    text-align: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .edit-actions {
    justify-content: center;
  }
  
  :deep(.el-form) {
    label-width: 80px !important;
  }
  
  :deep(.el-col) {
    margin-bottom: 10px;
  }
}

@media (max-width: 480px) {
  :deep(.el-dialog) {
    width: 95% !important;
  }
  
  .stats-item {
    padding: 12px 0;
  }
  
  .stats-label,
  .stats-value {
    font-size: 13px;
  }
}
</style>